//
//  TicketProductViewController.m
//  SXH
//
//  Created by 房 国生 on 15/6/26.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "TicketProductViewController.h"
#import "YYAnimationIndicator.h"
#import "TicketProductTableViewCell.h"
#import "OrderEnsureViewController.h"
#import "CommonService.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "LoginViewController.h"
#import "ProductEntity.h"
#import "StoreEntity.h"
#import "WebViewController.h"

@interface TicketProductViewController (){
    YYAnimationIndicator *indicator;
    
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    int page;
}

@property (nonatomic, strong) IBOutlet UITableView *tabelViewTickets;
@property (nonatomic, strong) IBOutlet UILabel *city_title;
@property (nonatomic, strong) IBOutlet UILabel *city_introduce;
@property (nonatomic, strong) NSMutableArray *mutableArrayTickets;

@end

@implementation TicketProductViewController
@synthesize tabelViewTickets;
@synthesize mutableArrayTickets;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    mutableArrayTickets = [[NSMutableArray alloc]init];
    page = 1;
    [self addHeader];
    [self addFooter];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [mutableArrayTickets count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *couponTableViewCellIdentifier=@"TicketProductTableViewCell";
    TicketProductTableViewCell *cell = (TicketProductTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"TicketProductTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    ProductEntity *productEntity = [mutableArrayTickets objectAtIndex:indexPath.row];
    [cell.image sd_setImageWithURL:[NSURL URLWithString:productEntity.album_thumb]];
    cell.name.text = productEntity.product_title;
    cell.price.text = [NSString stringWithFormat:@"¥ %@" ,productEntity.sale_price];
    cell.originPrice.text = [NSString stringWithFormat:@"¥ %@" ,productEntity.old_price];
    cell.ticketInfo.text = productEntity.descriptionInfo;
    cell.btnTicketBook.tag = indexPath.row;
    [cell.btnTicketBook addTarget:self action:@selector(ticketBook:) forControlEvents:UIControlEventTouchUpInside];
    cell.btnTicketIntroduce.tag = indexPath.row;
    [cell.btnTicketIntroduce addTarget:self action:@selector(ticketIntroduce:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
}

-(void)ticketBook:(id)sender
{
    UserEntity *userEntity = [UserEntity sharedInstance];
    if (userEntity.login == NO) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    UIButton *btn = (UIButton*)sender;
    ProductEntity *entity = [mutableArrayTickets objectAtIndex:btn.tag];;
    OrderEnsureViewController *vc = [[OrderEnsureViewController alloc]init];
    vc.productEntity = entity;
    vc.userEntity = userEntity;
    [[self navigationController] pushViewController:vc animated:YES];
}

- (void) getTicketsList:(int) pageNo RefreshView:(MJRefreshBaseView *)refreshView {
    indicator = [[YYAnimationIndicator alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-40, self.view.frame.size.height/2-40, 80, 57)];
    [indicator setLoadText:Loading_Text];
    [self.view addSubview:indicator];
    
    [indicator startAnimation];  //开始转动
    
    NSString *strPageNo = [NSString stringWithFormat:@"%d", pageNo];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           _city_id, @"city_id",
                           _park_id, @"park_id",
                           strPageNo, @"page",
                           @"10", @"limit",nil];
    
    [service getNetWorkData:param
                       Path:PARK_TICKET
                  Successed:^(id entity) {
                      if (pageNo ==1) {
                          [mutableArrayTickets removeAllObjects];
                          page = 1;
                      }
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [[dic objectForKey:@"data"] objectForKey:@"store_list"];
                      for (NSDictionary* attributes in array) {
                          StoreEntity *entity = [[StoreEntity alloc] init];
                          entity = [entity initWithAttributes:attributes];
                          for(NSDictionary* item in entity.product_list){
                              if([[item valueForKeyPath:@"park_id"] isEqualToString:_park_id]){
                                  [mutableArrayTickets insertObject:item atIndex:0];
                              }else{
                                  [mutableArrayTickets addObject:item];
                              }
                          }
                      }
                      if([mutableArrayTickets count]>0){
                          _city_introduce.text = [NSString stringWithFormat:@"%@热门景区",[[mutableArrayTickets objectAtIndex:0] valueForKeyPath:@"city_name"]];
                      }else{
                          _city_introduce.text = @"暂无相关门票销售";
                      }
                      [indicator stopAnimationWithLoadText:HasLoaded_Text withType:YES];
                      [self doneWithView:refreshView];
//                      dispatch_async(dispatch_get_main_queue(), ^{
//                          [tabelViewTickets reloadData];
//                      });
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [self doneWithView:refreshView];
                      [indicator stopAnimationWithLoadText:LoadFail_Text withType:YES];
                  }];
    
}

- (void)addFooter
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tabelViewTickets;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        ++page;
        [self getTicketsList:page RefreshView:refreshView];
        
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
}

- (void)addHeader
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tabelViewTickets;
    
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        [self getTicketsList:1 RefreshView:refreshView];
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
                
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
                
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.tabelViewTickets reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"TicketProductViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"TicketProductViewController"];
}

-(void)ticketIntroduce:(UIButton *)btn{
    ProductEntity *productEntity = [mutableArrayTickets objectAtIndex:btn.tag];
    WebViewController *vc = [[WebViewController alloc] init];
    vc.url = productEntity.product_introduce;
    vc.vcTitle = @"票型说明";
    [self.navigationController pushViewController:vc animated:YES];
}

@end
